package com.phpxiu.app.view;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.phpxiu.app.config.Constants;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.model.Permission;
import com.phpxiu.app.model.UploadResultInfo;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.OKHttpResponseModel;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.presenters.viewinterface.UploadView;
import com.phpxiu.app.upload.TUploadHelper;
import com.phpxiu.app.utils.FileManager;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.custom.FrescoImageView;
import com.phpxiu.app.view.custom.IFrescoImageView;
import com.phpxiu.app.view.custom.MEditText;
import com.phpxiu.app.view.custom.WindowLayout;
import com.phpxiu.app.view.dialog.PhotoOptionMenus;

import java.util.Timer;
import java.util.TimerTask;


/**
 * 用户提交认证表单界面
 * Created by WuJinZhou on 2016/6/7.
 */
public class UserAuthentication extends UIBase implements View.OnClickListener,View.OnTouchListener,UploadView {
    public final static String TAG="UserAuthentication";
    private final static int COUNT_DOWN_HANDLE=0x1;
    private final static int COUNT_DOWN_HANDLE_STATE=0x2;
    public final static int REQUEST_GET_REGION_CODE=0x3;
    private WindowLayout mainView;
    private MEditText nameInput,cardInput,phoneInput;
    private MEditText codeInput;
    private Button requestCodeBtn;
    private ImageButton cleanName,cleanID,cleanPhone;
    private IFrescoImageView cardPhoto;
    private FrescoImageView examplePic;
    private boolean isSubmit=false;
    private String photoPath;
    private String imageKey;
    private OKHttpParam param;
    private RelativeLayout loadingBox;
    private ImageView loadingImage;
    private AnimationDrawable uploadAni;
    private TUploadHelper uploader;
    private PhotoOptionMenus photoMenus;

    private int maxTime=60;
    private boolean isCountDownEnd=true;//倒计时结束
    private Timer timer;
    private TimerTask task;
    private OKHttpParam checkParam;
    private boolean isSubmitSuccess=false;//认证提交成功
    private Button submitBtn;

    private String regionCode="";
    private TextView regionView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_authentication);
        findViewById(R.id.top_bar_back_btn).setOnClickListener(this);
        mainView=(WindowLayout)findViewById(R.id.root_view);
        mainView.setOnTouchListener(this);
        findViewById(R.id.info_box).setOnTouchListener(this);
        findViewById(R.id.photo_box).setOnTouchListener(this);
        findViewById(R.id.notice_view).setOnTouchListener(this);
        submitBtn=(Button)findViewById(R.id.submit_btn);
        submitBtn.setOnClickListener(this);
        init();
        isSubmitSuccess=false;
    }

    /**
     * 初始化视图
     */
    private void init(){
        regionCode=getString(R.string.default_region_code);
        findViewById(R.id.region_list_link).setOnClickListener(this);
        regionView=(TextView)findViewById(R.id.region_name);
        regionView.setText(getString(R.string.default_country_name)+"("+regionCode+")");
        nameInput=(MEditText)findViewById(R.id.real_name_view);
        cleanName=(ImageButton)findViewById(R.id.name_input_clean_btn);
        nameInput.addTextChangedListener(new InputTextWatcher(cleanName));
        cleanName.setOnClickListener(this);
        cardInput=(MEditText)findViewById(R.id.card_number_view);
        cleanID=(ImageButton)findViewById(R.id.card_number_input_clean_btn);
        cardInput.addTextChangedListener(new InputTextWatcher(cleanID));
        cleanID.setOnClickListener(this);
        phoneInput=(MEditText)findViewById(R.id.phone_number_view);
        cleanPhone=(ImageButton)findViewById(R.id.phone_number_input_clean_btn);
        phoneInput.addTextChangedListener(new InputTextWatcher(cleanPhone));
        cleanPhone.setOnClickListener(this);
        codeInput=(MEditText)findViewById(R.id.code_input_view);
        codeInput.addTextChangedListener(new InputTextWatcher(null));
        cardPhoto=(IFrescoImageView)findViewById(R.id.card_photo);
        cardPhoto.setOnClickListener(this);
        examplePic=(FrescoImageView)findViewById(R.id.example_image);
        examplePic.setImageURI(Uri.parse("res:///"+ R.drawable.user_verify_example_image));
        loadingBox=(RelativeLayout)findViewById(R.id.loading_box);
        loadingImage=(ImageView)findViewById(R.id.loading_pic_view);
        uploadAni=(AnimationDrawable)loadingImage.getBackground();
        uploader=new TUploadHelper(this,this,"idcard");

        requestCodeBtn=(Button)findViewById(R.id.authentication_request_code_btn);
        requestCodeBtn.setEnabled(false);
        requestCodeBtn.setOnClickListener(this);
        countDown();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (v.getId()){
            case R.id.notice_view:
            case R.id.root_view:
            case R.id.info_box:
            case R.id.photo_box:
                hideSoftInput(nameInput);
                break;
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_bar_back_btn:
                onBackPressed();
                break;
            case R.id.region_list_link:
                Intent r=new Intent(this,UICountryCodePicker.class);
                startActivityForResult(r,REQUEST_GET_REGION_CODE);
                break;
            case R.id.authentication_request_code_btn:
                requestCode();
                codeInput.requestFocus();
                break;
            case R.id.submit_btn:
                if(!isSubmit){
                    submit();
                }
                break;
            case R.id.card_photo:
                if(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP){
                    requestMyPermissions(Permission.REQUEST_PHOTO);
                }else {
                    goPickPhoto();
                }
                break;
            case R.id.name_input_clean_btn:
                nameInput.setText("");
                break;
            case R.id.card_number_input_clean_btn:
                cardInput.setText("");
                break;
            case R.id.phone_number_input_clean_btn:
                phoneInput.setText("");
                break;
            default:
                break;
        }
    }

    /**
     * 点击发送，请求验证码
     */
    final private void requestCode(){
        maxTime=60;
        if(checkParam==null){
            checkParam=OKHttpParam.builder();
        }
        checkParam.put("phone",phoneInput.getText().toString());
        checkParam.put("type","login");
        checkParam.put("code",regionCode);
        requestCodeBtn.setEnabled(false);
        OKHttp.post(HttpConfig.API_CHECK_PHONE, checkParam.jsonParam(), TAG, new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {
                OKHttpResponseModel m = (OKHttpResponseModel) model;
                KKYUtil.log("验证手机结果：" + m.getResponseStr());
                handler.sendEmptyMessage(COUNT_DOWN_HANDLE_STATE);
            }

            @Override
            public void onErr(String errMsg) {
                mainView.showTopMsg(errMsg);
                requestCodeBtn.setEnabled(true);
            }
        });
    }

    /**
     * 倒计时
     */
    final private void countDown(){
        if(timer==null){
            timer=new Timer(true);
        }
        if(task==null){
            task=new TimerTask() {
                @Override
                public void run() {
                    handler.sendEmptyMessage(COUNT_DOWN_HANDLE);
                }
            };
        }
        timer.schedule(task,0,1000);
    }

    @Override
    public void handleMsg(Message msg) {
        switch (msg.what){
            case COUNT_DOWN_HANDLE:
                if(maxTime>0){
                    if(!isCountDownEnd) {
                        maxTime--;
                        requestCodeBtn.setText(maxTime+"S");
                    }
                }else {
                    handler.removeCallbacksAndMessages(null);
                    maxTime=60;
                    requestCodeBtn.setText(getString(R.string.ui_register_request_code_title));
                    if(TextUtils.getTrimmedLength(phoneInput.getText())>5){
                        if(!requestCodeBtn.isEnabled()){
                            requestCodeBtn.setEnabled(true);
                        }
                    }else{
                        if(requestCodeBtn.isEnabled()){
                            requestCodeBtn.setEnabled(false);
                        }
                    }
                    isCountDownEnd=true;
                }
                break;
            case COUNT_DOWN_HANDLE_STATE:
                isCountDownEnd=false;
                break;
            default:
                break;
        }
    }

    /**
     * 选择照片
     */
    private void goPickPhoto(){
        if(photoMenus==null){
            photoMenus=new PhotoOptionMenus(this);
            photoMenus.getWindow().getAttributes().width=(int)KKYApp.screenWidth;
        }
        photoMenus.show(false);
    }

    /**
     * 检测表单是否能提交
     */
    private void checkSubmit(){
        boolean nameValid=!TextUtils.isEmpty(nameInput.getText());
        int cardLen=TextUtils.getTrimmedLength(cardInput.getText());
        //boolean cardValid=(cardLen==15||cardLen==18);
        boolean cardValid=cardLen>0;
        boolean phoneValid=TextUtils.getTrimmedLength(phoneInput.getText())>5;
        boolean codeValid=TextUtils.getTrimmedLength(codeInput.getText())>3;
        boolean picValid=!TextUtils.isEmpty(imageKey);
        if(nameValid&&cardValid&&phoneValid&&picValid&&codeValid){
            if(!submitBtn.isEnabled()){
                submitBtn.setEnabled(true);
            }
        }else{
            if(submitBtn.isEnabled()){
                submitBtn.setEnabled(false);
            }
        }
    }

    /**
     * 提交表单
     */
    private void submit(){
        if(isSubmitSuccess){
            return;
        }

        if(imageKey==null||"".equals(imageKey)){
            mainView.showTopMsg(getString(R.string.authentication_card_pic_required));
            return;
        }

        if(param==null){
            param=OKHttpParam.builder(false);
        }
        param.put("name",nameInput.getText().toString().trim());
        param.put("phone",regionCode+phoneInput.getText().toString().trim());
        param.put("idcard",cardInput.getText().toString().trim());
        param.put("code",codeInput.getText().toString());
        param.put("idcard_img",imageKey);
        isSubmit=true;
        OKHttp.post(HttpConfig.API_USER_VERIFY, param.jsonParam(), TAG, new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {
                OKHttpResponseModel m = (OKHttpResponseModel) model;
                KKYUtil.log("认证结果：" + m.getResponseStr());
                isSubmit = false;
                MySelfInfo.getInstance().updateCacheString(UserAuthentication.this,Constants.USER_VERIFY_STATE,"1");//提交成功，则更改状态
                isSubmitSuccess=true;
                //mainView.showTopMsg(getString(R.string.user_verify_success_top_msg));
            }

            @Override
            public void onErr(String errMsg) {
                isSubmit = false;
                isSubmitSuccess=false;
                mainView.showTopMsg(errMsg);
            }
        });
    }

    /**
     * 关闭键盘
     */
    protected void hideSoftInput(View input) {
        if(input == null) return;
        InputMethodManager imm = (InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(input.getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==PhotoOptionMenus.REQUEST_PHOTO_CODE){//取到用于剪切的图片
            if(resultCode== Activity.RESULT_OK){
                if(data!=null&&data.getData()!=null){
                    Intent preview=new Intent(this, PicturePreview.class);
                    preview.putExtra(PicturePreview.PREVIEW_ACTION,PicturePreview.UPLOAD);
                    photoPath = FileManager.getFilePath(this,data.getData());
                    preview.setData(data.getData());
                    startActivityForResult(preview, PhotoOptionMenus.REQUEST_PREVIEW_CODE);
                }
            }else{
                photoPath=null;
            }
        }else if(requestCode==PhotoOptionMenus.REQUEST_CAPTURE_CODE){//拍到用于剪切的图片
            if(resultCode== Activity.RESULT_OK){
                Intent preview=new Intent(this, PicturePreview.class);
                preview.putExtra(PicturePreview.PREVIEW_ACTION,PicturePreview.UPLOAD);
                photoPath = FileManager.getFilePath(this,photoMenus.getTempUri());
                preview.setData(photoMenus.getTempUri());
                startActivityForResult(preview, PhotoOptionMenus.REQUEST_PREVIEW_CODE);
                KKYUtil.log(TAG,"拍照图片路径="+photoPath);
            }else{
                photoPath=null;
            }
        }else if(requestCode==PhotoOptionMenus.REQUEST_PREVIEW_CODE){
            if(resultCode== Activity.RESULT_OK){
                if(photoPath!=null){
                    uploadPic();
                }
            }
        }else if(requestCode==REQUEST_GET_REGION_CODE){//选择国际区号结果
            if(resultCode==RESULT_OK){
                regionCode=data.getStringExtra(UICountryCodePicker.SELECTED_CODE);
                String regionInfo=data.getStringExtra(UICountryCodePicker.SELECTED_COUNTRY)+"("+regionCode+")";
                regionView.setText(regionInfo);
            }
        }
    }

    /**
     * 上传头像
     */
    public void uploadPic(){
        if(loadingBox.getVisibility()==View.GONE) {
            loadingBox.setVisibility(View.VISIBLE);
            uploadAni.start();
        }
        uploader.uploadCover(photoPath);
    }

    @Override
    public void onUploadProcess(int percent) {
        //uploadPro.setText(percent+ "%");
    }

    @Override
    public void onUploadResult(int code, UploadResultInfo resultInfo) {
        if (0 == code) {
            KKYUtil.log("图片上传成功："+resultInfo.getKey());
            imageKey=resultInfo.getKey();
            cardPhoto.setImageURI(Uri.parse(resultInfo.getUrl()));
            checkSubmit();
        } else {
            //mainView.showTopMsg(getString(R.string.user_verify_upload_fail)+"："+code);
        }
        if (loadingBox.getVisibility() == View.VISIBLE) {
            loadingBox.setVisibility(View.GONE);
            uploadAni.stop();
        }
    }

    @Override
    public void onUploadResult(int code, String key) {

    }

    @Override
    protected void onPermission(int requestCode) {
        goPickPhoto();
    }

    @Override
    public void finish() {
        if(isSubmitSuccess){
           setResult(RESULT_OK);
        }
        super.finish();
    }

    /**
     * 密码输入监听
     */
    class InputTextWatcher implements TextWatcher {
        private View view;

        InputTextWatcher(View view) {
            this.view = view;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(view!=null){
                if(TextUtils.isEmpty(s)){
                    if(view.getVisibility()==View.VISIBLE){
                        view.setVisibility(View.INVISIBLE);
                    }
                }else{
                    if(view.getVisibility()!=View.VISIBLE){
                        view.setVisibility(View.VISIBLE);
                    }
                }
                if(view.getId()==R.id.phone_number_input_clean_btn&&isCountDownEnd){
                    if(TextUtils.getTrimmedLength(s)>5){
                        if(!requestCodeBtn.isEnabled()){
                            requestCodeBtn.setEnabled(true);
                        }
                    }else{
                        if(requestCodeBtn.isEnabled()){
                            requestCodeBtn.setEnabled(false);
                        }
                    }
                }
            }
            checkSubmit();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }
}
